package com.ourcraft.informationcollectionsystem.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.ourcraft.informationcollectionsystem.utils.authority.JWTUtils;
import com.ourcraft.informationcollectionsystem.utils.response.Result;
import com.ourcraft.informationcollectionsystem.utils.response.ResultCode;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;

public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Token");
        // 判断是否有token
        if (token == null) return true;
        // 验证token
        String result = JWTUtils.validateToken(token);
        // 根据验证结果返回不同的结果
        switch (result) {
            case "valid" -> {
                return true;
            }
            case "expired" -> {
                // token过期
                response.setContentType("application/json; charset=UTF-8");
                response.setStatus(HttpServletResponse.SC_OK);
                response.getWriter().write(JSONObject.toJSONString(Result.fail(ResultCode.TOKEN_EXPIRED)));
                return false;
            }
            case "wrong" -> {
                // token错误
                response.setContentType("application/json; charset=UTF-8");
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
                response.getWriter().write(JSONObject.toJSONString(Result.fail("Token 错误")));
                return false;
            }
            default -> {
                return false;
            }
        }
    }
}
